package com.example.mq.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.common.interpretor.AuthorizationHeaderInterceptor;
import com.example.mq.provider.KafkaProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.PostConstruct;

@RestController
@RequestMapping("/mq")
public class MqController {
    @Autowired
    private RestTemplate restTemplate;
    private final  static  String CLIENT_ID ="admin";
    private final  static  String CLIENT_SECRET ="123456";
    private final  static  String GRANT_TYPE ="client_credentials";
    private final  static  String TOKEN_REQUEST_URL ="http://localhost:8063/oauth/token";
    private final  static  String URL ="http://localhost:8063";
    private Logger logger = LoggerFactory.getLogger(MqController.class);
    @Autowired
    private KafkaProvider kafkaProvider;
    @Autowired
    private DiscoveryClient discoveryClient;
    @GetMapping("/qq")
    public String mq(){
        //设置请求头
        setHeaderToken();
        //发起请求
        Object reqUrl = getReqRes("/consumer");
        logger.info("请求结果:{}",JSON.toJSONString(reqUrl));
        return "mq";
    }
    @PreAuthorize("hasAuthority('system:dept:list')")
    @GetMapping("/mm")
    public String mm(){
        return "mm";
    }


    @GetMapping("/sendMsg")
    public void sendMsg(){
        for (int i =1;i<=2000000;i++){
            kafkaProvider.sendMessage("yourTopic","我来了。。。"+i);
        }




    }





    public void  setHeaderToken(){
        // 创建MultiValueMap来存储表单数据
        MultiValueMap<String, String> formData = new LinkedMultiValueMap<>();
        formData.add("client_id", CLIENT_ID);
        formData.add("client_secret", CLIENT_SECRET);
        formData.add("grant_type", GRANT_TYPE);
        // 设置请求头，指明内容类型为application/x-www-form-urlencoded
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        // 创建HttpEntity，它包装了表单数据和请求头
        HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(formData, headers);
        // 发送POST请求
        Object response = restTemplate.postForObject(TOKEN_REQUEST_URL, requestEntity, Object.class);
        JSONObject jsonObject = JSON.parseObject(JSONObject.toJSONString(response));
        String  access_token  = jsonObject.getString("access_token");
        // 创建拦截器
        AuthorizationHeaderInterceptor interceptor = new AuthorizationHeaderInterceptor(access_token);
        // 将拦截器添加到RestTemplate
        restTemplate.getInterceptors().add(interceptor);
    }
   public   Object getReqRes(String path){
       ServiceInstance services= discoveryClient.getInstances("consumer-service").get(0);
       String host  = services.getHost();
       int port = services.getPort();
       StringBuffer  reqUrl =  new StringBuffer();
       reqUrl.append("http://");
       reqUrl.append(host);
       reqUrl.append(":"+port);
       String res  = restTemplate.getForObject(reqUrl.toString()+path,String.class);
       return res;
   }





}
